﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // DoWork(); 

            CorrectNames(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\Database\Testing\x");
        }

        private static void DoWork()
        {
            string Path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\DB";

            string oldName = "BothHandsPullUp";
            string newName = "BothHandsPushUp";

            ChangeName(Path, oldName, newName);
        }

        private static void ChangeName(string Path,string oldName,string newName)
        {
 	        string[] directories = Directory.GetDirectories(Path);
            string[] files = Directory.GetFiles(Path);

            foreach (string s in files)
            {
                if (s.Contains(oldName))
                {
                    using (TextReader reader = File.OpenText(s))
                    {
                        string oldContext = reader.ReadToEnd();
                        string newContext = oldContext.Replace(oldName, newName);

                        reader.Close();

                        using (TextWriter writer = File.CreateText(s))
                        {
                            writer.Write(newContext);
                            writer.Close();
                        }                        
                    }

                    Directory.Move(s, s.Replace(oldName, newName));
                }
            }

            foreach(string s in directories)
            {
                string dirName = s;

                if(s.Contains(oldName))
                {
                    dirName = s.Replace(oldName, newName);
                    Directory.Move(s, dirName);
                }

                ChangeName(dirName, oldName, newName);
            }            
        }

        private static void CorrectNames(string Path)
        {
            string newDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\" + Guid.NewGuid();
            Directory.CreateDirectory(newDir);

            string[] directories = Directory.GetDirectories(Path);

            for (int i = 0; i < directories.Length; i++)
            {
                DirectoryInfo directory = new DirectoryInfo(directories[i]);
                string dirName = directory.Name;

                Directory.CreateDirectory(newDir + @"\" + dirName);

                string[] files = Directory.GetFiles(directories[i]);

                for (int j = 0; j < files.Length; j++)
                {
                    File.Copy(files[j], newDir + @"\" + dirName + @"\" + dirName + "_" + j.ToString("D3") + ".txt");
                }
            }
        }
    }
}
